<?php

namespace app\admin\controller;

class Admin extends Base
{
    //管理员列表
    public function all()
    {
        //查询出管理员列表后按是否超级管理员倒序排序，状态倒序排序并分页
        $admins = model('Admin')->order(['admin_is_super' => 'asc','admin_status' => 'asc'])->paginate(3);
        //定义模板数据变量
        $viewData = [
            'admins' => $admins
        ];
        $this->assign($viewData);
        return view();
    }

    //管理员添加
    public function add()
    {
        //接受数据
        if (request()->isAjax()){
            $data = [
                'admin_username' => input('post.admin_username'),
                'admin_password' => input('post.admin_password'),
                'conpass' => input('post.conpass'),
                'admin_nickname' => input('post.admin_nickname'),
                'admin_email' => input('post.admin_email')
            ];
            //将数据传递给模型并把结果返回给$result
            $result = model('Admin')->add($data);
            if ($result == 1){
                $this->success('管理员添加成功','admin/admin/all');
            }else{
                $this->error($result);
            }
        }
        return view();
    }

    //管理员状态操作
    public function status()
    {
        //接收数据
        $data = [
            'id' => input('post.id'),
            //若status值为1，则变为0，反之为1
            'status' => input('post.status') ? 0 : 1
        ];
        //从数据库里查询出id赋值给adminInfo
        $adminInfo = model('Admin')->find($data['id']);
        //将status更新为接收到的status
        $adminInfo->status = $data['status'];
        //更新
        $result = $adminInfo->save();
        if ($result){
            $this->success('操作成功','admin/admin/all');
        }else{
            $this->error('操作失败');
        }
    }

    //管理员编辑
    public function edit()
    {
        //接收数据
        if (request()->isAjax()){
            $data = [
                'id' => input('post.id'),
                'oldpass' => input('post.oldpass'),
                'newpass' => input('post.newpass'),
                'nickname' => input('post.nickname')
            ];
            //将数据传递给模型并把结果返回给$result
            $result = model('Admin')->edit($data);
            if ($result == 1){
                $this->success('管理员修改成功','admin/admin/all');
            }else{
                $this->error($result);
            }
        }
        //从数据库里查询出id
        $adminInfo = model('Admin')->find(input('id'));
        //定义模板变量
        $viewData = [
            'adminInfo' => $adminInfo
        ];
        //渲染
        $this->assign($viewData);
        return view();
    }

    //管理员删除
    public function del()
    {
        //从数据库里查询出id
        $adminInfo = model('Admin')->find(input('id'));
        $result = $adminInfo->delete();
        if ($result){
            $this->success('删除成功','admin/admin/all');
        }else{
            $this->error('删除失败');
        }
    }
}
